package com.moons.uvcdemo.util;

import android.graphics.Bitmap;

import com.moons.uvcdemo.config.DemoConfig;
import com.moons.uvcdemo.model.UserFace;
import com.moons.uvcdemo.util.ThreadPool.ThreadPoolManager;
import com.moons.uvcdemo.utils.ApplicationMe;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FaceDataUtil {
    private FaceDataUtil() {
    }

    public static FaceDataUtil getInstance() {
        return FaceDataUtilHolder.INSTANCE;
    }

    private static class FaceDataUtilHolder {
        private static final FaceDataUtil INSTANCE = new FaceDataUtil();
    }

    public static final ArrayList<UserFace> userFaces_all = new ArrayList<>();

    public void updateUsers() {
        synchronized (FaceDataUtil.userFaces_all) {
            userFaces_all.clear();
        }
        List<UserFace> userFaces = ApplicationMe.getInstance().getDaoSession().getUserFaceDao().loadAll();


        synchronized (FaceDataUtil.userFaces_all) {
            if (userFaces != null && !userFaces.isEmpty()) {
                userFaces_all.addAll(userFaces);
            }
        }
        userFaces.clear();
    }


    /**
     * @param face
     * @return 插入的数据在数据库中的行数, 例如1，2，3……
     */
    public long insert(UserFace face) {
        return ApplicationMe.getInstance().getDaoSession().getUserFaceDao().insertOrReplace(face);
    }

    public void update(UserFace face) {
        ApplicationMe.getInstance().getDaoSession().getUserFaceDao().update(face);
    }


    public void delete(UserFace face) {
        ApplicationMe.getInstance().getDaoSession().getUserFaceDao().delete(face);
        deleteUser(face.getId());
    }

    public boolean deleteUser(long id) {
        boolean bok = false;
        synchronized (FaceDataUtil.userFaces_all) {
            for (Iterator<UserFace> iterator = FaceDataUtil.userFaces_all.iterator(); iterator.hasNext(); ) {
                UserFace userFace = iterator.next();
                if (userFace.getId() == id) {
                    if (deletePicByID(id)) {
                        bok = true;
                        iterator.remove();
                        break;
                    }
                }
            }
        }
        return bok;
    }

    private boolean deletePicByID(long id) {

        String imgPath = DemoConfig.FacePicPath + id + ".jpg";
        File imgFile = new File(imgPath);
        if (imgFile.exists()) {
            return imgFile.delete();
        }
        return false;
    }


    public void deleteAll() {
        synchronized (FaceDataUtil.userFaces_all) {
            userFaces_all.clear();
        }

        deleteAllPictures();
        ApplicationMe.getInstance().getDaoSession().getUserFaceDao().deleteAll();

    }

    private void deleteAllPictures() {
        File pic_folder = new File(DemoConfig.FacePicPath);
        if (pic_folder.exists() && pic_folder.isDirectory()) {
            File[] files = pic_folder.listFiles();
            for (File file : files) {
                file.delete();
            }
        }
    }

    public static void SaveBitmap(final Bitmap bitmap, final File file) {

        ThreadPoolManager.getInstance().getBackgroundExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                if (bitmap == null) {

                } else {
                    boolean bret = false;
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
                        fos.flush();
                        FileDescriptor fd = fos.getFD();
                        fd.sync();
                        bret = true;
                    } catch (Exception var13) {
                        var13.printStackTrace();
                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException var12) {
                                var12.printStackTrace();
                            }
                        }

                    }

                }
            }
        });

    }

    public static float[] byteArr2floatArr(byte[] bArr) {
        ByteArrayInputStream bas = new ByteArrayInputStream(bArr);
        DataInputStream ds = new DataInputStream(bas);
        // 4 bytes per float
        float[] fArr = new float[bArr.length / 4];
        for (int i = 0; i < fArr.length; i++) {
            try {
                fArr[i] = ds.readFloat();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fArr;
    }

    public static byte[] floatArr2byteArr(float[] fArr) {
        ByteArrayOutputStream bas = new ByteArrayOutputStream();
        DataOutputStream ds = new DataOutputStream(bas);
        for (float f : fArr) {
            try {
                ds.writeFloat(f);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bas.toByteArray();
    }

    public static float GetVectorLength(float[] v) {
        float len = 0;
        for (float vi : v) {
            len += Math.pow(vi, 2);
        }
        len = (float) Math.sqrt(len);
        return len;
    }

    public static float calcCosValue_accel(float[] v1, float v1_len, float[] v2, float v2_len, int length) {
        float top = 0;
        for (int i = 0; i < length; i++) {
            top += v1[i] * v2[i];
        }
        if (v1_len == 0 || v2_len == 0) {
            return Float.MIN_NORMAL;
        }
        return top / (v1_len * v2_len);
    }
}
